//
//  VGLoadingView.swift
//  vgbox
//
//  Created by 小琦 on 2019/4/9.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import UIKit

class VGLoadingView: UIView {

        weak var vc: UIViewController!

        fileprivate var middleImageView: UIImageView = {
            let imageView: UIImageView = UIImageView()
            imageView.image = UIImage(named: "loadingB")
            imageView.rotate360DegreeWithImageView(duration: 1.5, repeatCount: Float(CGFloat.greatestFiniteMagnitude))
            imageView.sizeToFit()
            return imageView
        }()

        fileprivate var tipLb: UILabel = {
            let lb: UILabel = UILabel()
            lb.textColor = Constant.color_104
            lb.font = UIFont.systemFont(ofSize: 13)
            lb.text = "加载中..."
            lb.textAlignment = .center
            return lb
        }()

        init(viewController: UIViewController) {
            super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            self.vc = viewController
            initViews()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }


        public func show()
        {
            middleImageView.rotate360DegreeWithImageView(duration: 1.5, repeatCount: Float(CGFloat.greatestFiniteMagnitude))
            self.vc.view.addSubview(self)
        }
    
        public func close()
        {
            self.removeFromSuperview()
        }
    
        fileprivate func initViews()
        {
            self.backgroundColor = UIColor.white
            addSubview(middleImageView)
            addSubview(tipLb)
         
            middleImageView.snp.makeConstraints { (make) in
                make.center.equalToSuperview()
                make.width.equalTo(35)
                make.height.equalTo(35)
            }
         
            tipLb.snp.makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(middleImageView.snp.bottom).offset(10)
                make.height.equalTo(24)
                make.width.equalTo(100)
        }
    }
}
extension UIImageView{
    //图片旋转
    func rotate360DegreeWithImageView(duration:CFTimeInterval , repeatCount :Float ) {
        
        //让其在z轴旋转
        let rotationAnimation  = CABasicAnimation(keyPath: "transform.rotation.z")
        
        //旋转角度
        rotationAnimation.toValue = NSNumber(value: Double.pi * (-2.0) )
        
        //旋转周期
        rotationAnimation.duration = duration
        
        //旋转累加角度
        rotationAnimation.isCumulative = true
        
        //旋转次数
        rotationAnimation.repeatCount = repeatCount
        
        self.layer .add(rotationAnimation, forKey: "rotationAnimation")
        
    }
    //停止旋转
    func stopRotate() {
        self.layer.removeAllAnimations()
    }
}
